package com.flux.utils

import android.util.Log
import java.io.File
import org.json.JSONException
import org.json.JSONArray
import org.json.JSONObject

/**
 * Log工具类
 * Created on 2017/12/4.
 *
 * @author Yang
 */
object LogUtil {

    var isDebugEnabled = true

    private var tag = "SunflowerBao"

    private val line_separator = System.getProperty("line.separator")

    fun v(msg: String) {
        if (isDebugEnabled) {
            val element = Thread.currentThread().stackTrace[3]
            val tmp = "[" + element.fileName + "," + element.className.substring(element.className.lastIndexOf(".")) + "," + element.methodName + "," + element.lineNumber + "]"
            Log.v(tag, msg + tmp)
        }
    }

    fun i(tag:String, msg: String) {
        if (isDebugEnabled) {
            val element = Thread.currentThread().stackTrace[3]
            val tmp = "[" + element.fileName + "," + element.className.substring(element.className.lastIndexOf(".")) + "," + element.methodName + "," + element.lineNumber + "]"
            Log.i(tag, unicodeToUTF8(msg)!! + tmp)
        }
    }

    fun i(msg: String) {
        if (isDebugEnabled) {
            val element = Thread.currentThread().stackTrace[3]
            val tmp = "[" + element.fileName + "," + element.className.substring(element.className.lastIndexOf(".")) + "," + element.methodName + "," + element.lineNumber + "]"
            Log.i(tag, unicodeToUTF8(msg)!! + tmp)
        }
    }

    fun e(msg: String) {
        if (isDebugEnabled) {
            val element = Thread.currentThread().stackTrace[3]
            val tmp = "[" + element.fileName + "," + element.className.substring(element.className.lastIndexOf(".")) + "," + element.methodName + "," + element.lineNumber + "]"
            Log.e(tag, msg + tmp)
        }
    }

    fun enter(msg: String) {
        printByType(tag, "enter", msg)
    }

    fun enter(tag: String, msg: String) {
        printByType(tag, "enter", msg)
    }

    private fun printByType(tag: String, type: String, msg: String) {
        val elements = Thread.currentThread().stackTrace
        if (isDebugEnabled) {
            if (null == elements || elements.size < 4) {
                return
            }

            val e = elements[4]
            var file: String? = e.fileName
            var cls = e.className
            val method = e.methodName
            val line = e.lineNumber

            if (file != null && file.lastIndexOf(File.separator) >= 0) {
                file = file.substring(file.lastIndexOf(File.separator))
            }
            if (cls.lastIndexOf(".") >= 0) {
                cls = cls.substring(cls.lastIndexOf("."))
            }
            Log.d(tag, "[$file]$cls.$method($msg)$type at line:$line")
        }
    }

    @JvmStatic
    fun printStackTrace(flag: Array<String>) {
        var flg = tag
        if (1 == flag.size) {
            flg = flag[0]
        }
        val elements = Thread.currentThread().stackTrace
        for (i in elements.indices) {
            Log.d(flg, " FILE:" + elements[i].fileName + ", CLASS:" + elements[i].className + ", METHOD:" + elements[i].methodName + ", LINE" + elements[i].lineNumber)
        }
    }

    private fun unicodeToUTF8(src: String?): String? {
        if (null == src) {
            return null
        }
        val out = StringBuilder()
        var i = 0
        while (i < src.length) {
            val c = src[i]
            if (i + 6 < src.length && c == '\\' && src[i + 1] == 'u') {
                val hex = src.substring(i + 2, i + 6)
                try {
                    out.append(Integer.parseInt(hex, 16).toChar())
                } catch (nfe: NumberFormatException) {
                    nfe.fillInStackTrace()
                }

                i += 6
            } else {
                out.append(src[i])
                ++i
            }
        }
        return out.toString()
    }

    private fun printLine(tag: String, isTop: Boolean) {
        if (isTop) {
            Log.d(tag, "╔═══════════════════════════════════════════════════════════════════════════════════════")
        } else {
            Log.d(tag, "╚═══════════════════════════════════════════════════════════════════════════════════════")
        }
    }

    fun printDivider() {
        Log.d(tag, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    }

    fun printJson(msg: String) {

        var message: String

        message = try {
            when {
                msg.startsWith("{") -> {
                    val jsonObject = JSONObject(msg)
                    jsonObject.toString(4)
                }
                msg.startsWith("[") -> {
                    val jsonArray = JSONArray(msg)
                    jsonArray.toString(4)
                }
                else -> msg
            }
        } catch (e: JSONException) {
            msg
        }

        printLine(tag, true)
        message = "" + line_separator + message
        val lines = message.split(line_separator.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
        for (line in lines) {
            Log.d(tag, line)
        }
        printLine(tag, false)
    }
}
